{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设置全局字体，避免中文乱码\n",
    "plt.rcParams['figure.dpi'] = 300  # 提高所有图形的分辨率\n",
    "config = {\n",
    "    \"font.family\": 'serif',\n",
    "    \"font.size\": 40,\n",
    "    \"mathtext.fontset\": 'stix',\n",
    "    \"font.serif\": ['SimSun'],  # 使用宋体，前提是系统安装了该字体\n",
    "}\n",
    "plt.rcParams.update(config)  # 更新配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "print(os.getcwd())  # 输出当前工作目录\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取 Excel 数据\n",
    "data = pd.read_excel('问题2.xlsx')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 选择峰值列 Bm\n",
    "peak_values = data['Bm']\n",
    "\n",
    "# 创建样本数数组\n",
    "sample_numbers = range(len(peak_values))\n",
    "\n",
    "# 可视化峰值分布\n",
    "plt.figure(figsize=(20, 12), dpi=300)  # 增加图形宽度和高度，并设置DPI为300\n",
    "\n",
    "# 使用“plasma”渐变色，颜色鲜明且美观\n",
    "cmap = plt.get_cmap(\"plasma\")  \n",
    "colors = [cmap(i / len(peak_values)) for i in range(len(peak_values))]\n",
    "\n",
    "# 先绘制连接线，使用浅灰色，设置较低的 zorder\n",
    "plt.plot(sample_numbers, peak_values, linestyle='-', color='#E0E0E0', linewidth=1.5, alpha=0.9, zorder=1)\n",
    "\n",
    "# 再绘制散点图，确保散点在连接线前面，设置较高的 zorder\n",
    "scatter = plt.scatter(sample_numbers, peak_values, color=colors, s=70, alpha=0.85, zorder=2)  # 增加散点大小并调整透明度\n",
    "\n",
    "plt.xlabel('样本数')\n",
    "plt.ylabel('峰值 (B$_m$)')\n",
    "plt.title('B$_m$ 峰值分布图')\n",
    "plt.grid(True, linestyle='--', alpha=0.7)\n",
    "\n",
    "# 设置横坐标标签，每100个样本显示一个标签，减少重叠\n",
    "plt.xticks(ticks=sample_numbers[::100])  \n",
    "plt.yticks()\n",
    "\n",
    "# 设置坐标轴范围\n",
    "plt.xlim(left=0, right=len(peak_values)-1)  # 横坐标轴从0开始，到最后一个样本\n",
    "plt.ylim(bottom=0)  # 纵坐标轴从0开始\n",
    "\n",
    "# 添加图例，包含所有渐变色，不带数字\n",
    "legend_handles = []\n",
    "for i in range(0, len(colors), len(colors) // 4):  # 每种颜色一个图例项\n",
    "    legend_handles.append(plt.Line2D([0], [0], marker='o', color='w', label='峰值 (B$_m$)颜色示例',\n",
    "                                     markerfacecolor=colors[i], markersize=10, alpha=0.8))\n",
    "\n",
    "plt.legend(handles=legend_handles, loc='upper right', fontsize=30)  # 将图例移动到右上角\n",
    "\n",
    "# 显示图形\n",
    "plt.tight_layout()  # 自动调整布局\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from scipy.stats import pearsonr\n",
    "\n",
    "# 设置全局字体，避免中文乱码\n",
    "plt.rcParams['figure.dpi'] = 300  # 提高所有图形的分辨率\n",
    "config = {\n",
    "    \"font.family\": 'serif',\n",
    "    \"font.size\": 14,\n",
    "    \"mathtext.fontset\": 'stix',\n",
    "    \"font.serif\": ['SimSun'],  # 使用宋体，前提是系统安装了该字体\n",
    "}\n",
    "plt.rcParams.update(config)  # 更新配置\n",
    "\n",
    "# 1. 读取Excel数据\n",
    "data = pd.read_excel('问题2.xlsx')\n",
    "\n",
    "# 检查数据是否加载正确\n",
    "print(data.head())\n",
    "\n",
    "# 2. 描述性统计分析\n",
    "print(\"\\n数据描述统计：\")\n",
    "print(data.describe())\n",
    "\n",
    "# 3. 计算温度和磁芯损耗的相关系数\n",
    "corr, p_value = pearsonr(data['温度'], data['磁芯损耗'])\n",
    "print(f\"\\n温度与磁芯损耗的相关系数: {corr:.4f}, p值: {p_value:.4f}\")\n",
    "\n",
    "# 4. 可视化温度与磁芯损耗的关系\n",
    "plt.figure(figsize=(8, 5))\n",
    "ax = plt.gca()  # 获取当前轴对象\n",
    "scatter = sns.scatterplot(x='温度', y='磁芯损耗', data=data, color='#1f77b4', alpha=0.7, edgecolor='w', s=50, label='磁芯损耗数据点')\n",
    "sns.regplot(x='温度', y='磁芯损耗', data=data, scatter=False, color='#ff7f0e', line_kws={\"linestyle\": \"--\"}, label='线性回归线')\n",
    "\n",
    "# 添加自定义图例项\n",
    "plt.legend(loc='upper left', fontsize=12, frameon=True)\n",
    "\n",
    "# 在图框内右侧并与图例对齐，显示相关系数和 p 值\n",
    "ax.text(0.75, 0.95, f\"相关系数: {corr:.4f}\\nP值: {p_value:.4f}\",\n",
    "        fontsize=12, color='black', ha='left', va='top',\n",
    "        bbox=dict(facecolor='white', alpha=0.6, boxstyle='round,pad=0.5'),\n",
    "        transform=ax.transAxes)\n",
    "\n",
    "plt.title('温度与磁芯损耗关系图')\n",
    "plt.xlabel('温度 (°C)')\n",
    "plt.ylabel('磁芯损耗')\n",
    "plt.grid(True, linestyle='--', alpha=0.6)\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "# 5. 分箱分析（将温度分为多个区间，分析每个区间的磁芯损耗均值）\n",
    "data['温度区间'] = pd.cut(data['温度'], bins=5)  # 可以根据数据调整bins数量\n",
    "mean_loss_by_temp = data.groupby('温度区间')['磁芯损耗'].mean().reset_index()\n",
    "\n",
    "# 可视化不同温度区间的磁芯损耗均值\n",
    "plt.figure(figsize=(10, 5.5))\n",
    "sns.barplot(x='温度区间', y='磁芯损耗', data=mean_loss_by_temp, palette='Blues_d')\n",
    "plt.title('不同温度区间的磁芯损耗均值')\n",
    "plt.xlabel('温度区间')\n",
    "plt.ylabel('磁芯损耗均值')\n",
    "plt.xticks(rotation=45)\n",
    "plt.grid(True, linestyle='--', alpha=0.6)\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py38torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
